package cn.occgmat.service.impl;

import cn.occgmat.entity.Admin;
import cn.occgmat.dao.AdminDao;
import cn.occgmat.service.AdminService;
import cn.occgmat.util.BaseResponse;
import cn.occgmat.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Administrator
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminDao adminDao;

    @Override
    public int adminUpdate(Admin admin) {
        return adminDao.adminUpdate(admin);
    }

    @Override
    public void logOut(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin != null) {
            // 修改用户状态
            admin.setState("离线");
            if (this.adminDao.setAdminState(admin) <= 0) {
                throw new RuntimeException("更新管理员状态失败！");
            }
            session.removeAttribute("admin");
        }
    }

    /**
     * 分页查询管理员信息
     *
     * @param page  当前页数
     * @param limit 每页数
     * @return json数据
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public BaseResponse<Admin> findAllLimit(int page, int limit) {
        int startPage = (page - 1) * limit;
        BaseResponse<Admin> baseResponse = new BaseResponse<>(StatusCode.Success);
        baseResponse.setData(adminDao.findAllLimit(startPage, limit));
        baseResponse.setCount(adminDao.getCount());
        return baseResponse;
    }

    /**
     * 管理员登录
     *
     * @param admin 管理员
     * @return 查询结果json数据
     */
    @Override
    public BaseResponse<?> findLogin(Admin admin, HttpSession session) {
        Admin loginAdmin = adminDao.findLogin(admin);
        BaseResponse<?> baseResponse;
        if (loginAdmin != null) {
            baseResponse = new BaseResponse<>(StatusCode.Success);
            // 修改用户状态
            loginAdmin.setState("在线");
            int result = adminDao.setAdminState(admin);
            if (result <= 0) {
                throw new RuntimeException("更新管理员状态失败！");
            }
            // 将管理员信息暂存到session
            session.setAttribute("admin", loginAdmin);
        } else {
            baseResponse = new BaseResponse<>(StatusCode.Fail);
        }
        return baseResponse;
    }
}
